package com.qf.sy2103.ssm.filter;

import lombok.extern.slf4j.Slf4j;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Collection;
import java.util.Enumeration;
import java.util.Map;
import java.util.Set;

@WebFilter(urlPatterns = "/*")
@Slf4j
public class RequestAnalysisFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        log.trace("初始化！");
    }

    @Override
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {

        HttpServletRequest request = (HttpServletRequest) req;

        // 请求行
        final String uri = request.getRequestURI();
        log.trace("uri:{}",uri);

        log.trace("请求头部分 ====================================");
        // 请求头
        final Enumeration<String> headerNames = request.getHeaderNames();

        while (headerNames.hasMoreElements()) {
            final String headerName = headerNames.nextElement();
            final String headerValue = request.getHeader(headerName);
            log.debug("{} ---> {}",headerName,headerValue);
        }

        log.trace("请求参数部分 ====================================");
        // 请求当中的参数获取
        final Map<String, String[]> parameterMap = request.getParameterMap();
        final Set<Map.Entry<String, String[]>> entries = parameterMap.entrySet();
        for (Map.Entry<String, String[]> entry : entries) {
            final String key = entry.getKey();
            final String[] value = entry.getValue();
            log.debug("{} ---> {}",key,value);
        }

        // 如果需要继执行filter之后的逻辑处理，需要放行。
        chain.doFilter(req,res);

        // 分析响应结果
        HttpServletResponse response = (HttpServletResponse) res;

        // 响应的状态码
        final int status = response.getStatus();
        log.trace("响应状态码:{}",status);
        log.trace("响应头部分 ====================================");
        final Collection<String> responseHeaderNames = response.getHeaderNames();
        for (String headerName : responseHeaderNames) {
            final String headerValue = response.getHeader(headerName);
            log.trace("{} ---> {}",headerName,headerValue);
        }

    }

    @Override
    public void destroy() {

    }
}
